package com.ce.sys.login.listener;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.ce.framework.constants.WebConstants;
import com.ce.sys.login.model.User;
import com.ce.util.SessionUtil;

/**
 * 嫦娥软件有限公司 版权所有 2013
 * 创建人： andy
 * 创建时间： 2013-11-4 上午09:45:46
 * 功能描述:登陆系统的用户操作类，用于清除或添加session中的已登录用户信息
 * ==================================
 * 修改历史
 * 修改人        修改时间      修改位置（函数名）
 *
 * ==================================
 */
public class LoginUserListener implements HttpSessionListener, HttpSessionAttributeListener,ServletContextListener,Serializable{
	private static final long serialVersionUID = 1L;
	
	public static final String USER_SESSION_ID = WebConstants.LOGIN_USER;
		
	/**
	 * 登陆系统的人员List
	 */
	private static List<User> list=new ArrayList<User>();
	private static List<String> idlist=new ArrayList<String>();
	private static List<HttpSession> slist=new ArrayList<HttpSession>();

	/**
	 * 在线人员数量
	 */
	private int onlineNum;
	
	private static LoginUserListener instance;
	
	private static String basePath;

	public static List<User> getList(){
		return(list);
	}
	
	public static List<String> getUserIdList(){
		return idlist;
	}

	public void attributeAdded(HttpSessionBindingEvent event) { 
		if (event.getName().equals(USER_SESSION_ID)) { 
			System.out.println("User logged in."); 
//			SessionUtil.saveSessionId();
			//判断当前的登录用户是否已经登陆过系统，未登陆就将该用户信息存入。
			User loginUser = (User)(event.getValue());
			for(int i=0;i<list.size();i++){
				User user = list.get(i);
				if(user.getVcId().equals(loginUser.getVcId()))
				   return;
			}
			list.add(loginUser);
			idlist.add(loginUser.getVcId());
		} 
	} 

	public synchronized void attributeRemoved(HttpSessionBindingEvent event) { 
		if (event.getName().equals(USER_SESSION_ID)) { 
			System.out.println("User logged out."); 
			SessionUtil.delSessionId(event.getSession().getId());
			removeUser((User)(event.getValue()));
			if(onlineNum>0)onlineNum--;
//			SessionUtil.removeSession(event.getSession());
		}
	}
	
	private void removeUser(User user){
		if(user==null){
			return;
		}
		for(int i=0;i<list.size();i++){
			if(user.equals(list.get(i))){
				list.remove(i);
				idlist.remove(user.getVcId());
				break;
			}
		}
	}

	public void contextDestroyed(ServletContextEvent event) {
		saveObject(this);
	}

	public void contextInitialized(ServletContextEvent event) {
		basePath = event.getServletContext().getRealPath("/");
		instance = this;
	}

	public void sessionCreated(HttpSessionEvent event) {
		HttpSession session = event.getSession();
		slist.add(session);
		onlineNum++;
	}

	public void sessionDestroyed(HttpSessionEvent event) {
		SessionUtil.delSessionId(event.getSession().getId());
		removeUser(User.getCurUser(event.getSession()));
		slist.remove(event.getSession());
		if(onlineNum>0)onlineNum--;
	}
	

	public static int getAllOnlineUserNumber(){
		if(instance==null)return 0;
		return instance.onlineNum;
	}

	public static int getLoginUserNumber(){
		return list.size();
	}
	
	public void saveObject(Object obj){
		String path = basePath+"/sessionListener.txt";
		try {
			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path));
			out.writeObject(obj);
			out.close();
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public Object getObject(){
		Object obj = null;
		try {
			String path = basePath+"/sessionListener.txt";
			ObjectInputStream in = new ObjectInputStream(new FileInputStream(path));
			obj = in.readObject();
			in.close();
			File f = new File(path);
			if(f.exists())
				f.delete();
		} catch (FileNotFoundException e) {
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return obj;
	}

	public void attributeReplaced(HttpSessionBindingEvent se) {
		// TODO Auto-generated method stub
	}
	
}
